package com.dd.ent.car.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.util.ImageUtils;
import com.dd.ent.car.common.util.SDCardUtil;
import com.dd.ent.car.common.util.ScreenUtils;
import com.dd.ent.car.common.xrichtext.ui.NewActivity;
import com.dd.ent.car.service.note.NoteService;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.BaseActivity;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pp.ent.base.concurrent.XLCommand;
import com.pp.ent.base.concurrent.XLCommandListener;
import com.pp.ent.base.concurrent.XLCommandResult;
import com.pp.ent.base.concurrent.XLThreadPool;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.ViewInject;
import com.qiniu.android.http.ResponseInfo;

import java.util.ArrayList;

import me.iwf.photopicker.PhotoPicker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.dd.ent.car.R.id.et_new_content;

/**
 * Created by dengqu on 2016/5/30.
 *
 * @author dengqu
 */
@ContentView(R.layout.activity_register_success)
public class RegisterSuccessActivity extends BaseActivity {

    private static final String TAG = "RegisterSuccessActivity";

    @ViewInject(R.id.titlebar_left)
    private View mBtnBack;
    @ViewInject(R.id.titlebar_title)
    private TextView mTvTitle;
    @ViewInject(R.id.layout_avatar)
    private View mLayoutAvatar;
    @ViewInject(R.id.layout_name_and_gender)
    private View mLayoutNicknameGender;
    @ViewInject(R.id.iv_user_avatar)
    private ImageView mIvAvatar;
    @ViewInject(R.id.et_nickname)
    private EditText mEtNickname;
    @ViewInject(R.id.iv_icon_nickname)
    private ImageView mIvNickname;
    @ViewInject(R.id.iv_clear_nickname)
    private ImageView mIvClearNickname;
    @ViewInject(R.id.layout_btn_gender_male)
    private View mLayoutMale;
    @ViewInject(R.id.layout_btn_gender_female)
    private View mLayoutFemale;
    @ViewInject(R.id.btn_complete)
    private View mBtnComplete;

    @Inject
    private UserService userService;
    @Inject
    private NoteService noteService;

    private final int MSG_UPDATE_USER_PORTRAIT = 109;

    private String mStrNickname;
    private boolean mIsNicknameNotEmpty = false;
    private boolean mIsClearPortraitCash;
    private Subscription subsInsert;
    private ProgressDialog insertDialog;
    private String smallImagePath;
    private String avthorUrl;

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, RegisterSuccessActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setListener();
    }

    private void initData() {
        mTvTitle.setText("完善个人资料");
        User user = userService.getUser();
        if (user != null) {
            mEtNickname.setText(user.getUserName());
            if ("m".equals(user.getSex())) {
                selectMale(true);
            } else if ("f".equals(user.getSex())) {
                selectMale(false);
            }
            avthorUrl = user.getAvathor();
            ImageLoader.getInstance().displayImage(avthorUrl, mIvAvatar);
        }
        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);
    }

    private void setListener() {
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mIvAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callGallery();
            }
        });
        mEtNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mIvClearNickname.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
                mStrNickname = s.toString().trim();
                mIsNicknameNotEmpty = mStrNickname.length() > 0;
                mBtnComplete.setEnabled(mIsNicknameNotEmpty && isGenderSelected());
            }
        });
        mEtNickname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mIvNickname.setImageDrawable(getResources().getDrawable(hasFocus ? R.drawable.icon_nickname_focused : R.drawable.icon_nickname));
            }
        });
        mIvClearNickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEtNickname.setText("");
            }
        });
        View.OnClickListener genderOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsNicknameNotEmpty) {
                    mBtnComplete.setEnabled(true);
                }
                switch (v.getId()) {
                    case R.id.layout_btn_gender_male:
                        selectMale(true);
                        break;
                    case R.id.layout_btn_gender_female:
                        selectMale(false);
                        break;
                }
            }
        };
        mLayoutMale.setOnClickListener(genderOnClickListener);
        mLayoutFemale.setOnClickListener(genderOnClickListener);
        mBtnComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XLThreadPool.sendCommand(new XLCommand() {
                    @Override
                    protected Object excute() throws Exception {
                        if (smallImagePath != null) {
                            ResponseInfo responseInfo = noteService.syncSumbitFile(smallImagePath);
                            MLog.debug("getEditData", responseInfo.path);
                            avthorUrl = "http://quydbezgk.hn-bkt.clouddn.com/" + responseInfo.response.optString("hash");
                        }
                        User user = userService.getUser();
                        user.setAvathor(avthorUrl);
                        user.setSex(getSelectedGender());
                        user.setUserName(mStrNickname);
                        userService.refreshUser(user);
                        userService.update();
                        return user;
                    }
                }, new XLCommandListener() {
                    @Override
                    public void onResponse(XLCommandResult xlCommandResult) {
                        if (xlCommandResult != null && xlCommandResult.isSuccessful()) {
                            userService.update();
                        }
                    }
                });
            }
        });
    }

    private void registerUserAvatarListener() {
    }

    /**
     * 调用图库选择
     */
    private void callGallery() {
        //调用第三方图库选择
        PhotoPicker.builder()
                .setPhotoCount(1)//可选择图片数量
                .setShowCamera(true)//是否显示拍照按钮
                .setShowGif(true)//是否显示动态图
                .setPreviewEnabled(true)//是否可以预览
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerUserAvatarListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mIsClearPortraitCash = true;
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                } else if (requestCode == PhotoPicker.REQUEST_CODE) {
                    //异步方式插入图片
                    insertImagesSync(data);
                }
            }
        }
    }


    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        subsInsert = Observable.create(new Observable.OnSubscribe<Bitmap>() {
            @Override
            public void call(Subscriber<? super Bitmap> subscriber) {
                try {
                    int width = ScreenUtils.getScreenWidth(RegisterSuccessActivity.this);
                    int height = ScreenUtils.getScreenHeight(RegisterSuccessActivity.this);
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    //可以同时插入多张图片
                    if (photos != null && photos.size() > 0) {
                        //Log.i("NewActivity", "###path=" + imagePath);
                        String imagePath = photos.get(0);
                        Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);//压缩图片
                        //bitmap = BitmapFactory.decodeFile(imagePath);
                        smallImagePath = SDCardUtil.saveToSdCard(bitmap);
                        //Log.i("NewActivity", "###imagePath="+imagePath);
                        subscriber.onNext(bitmap);
                    }
                    subscriber.onCompleted();
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                        showToast("设置头像成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast("设置头像失败:" + e.getMessage());
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        mIvAvatar.setImageBitmap(bitmap);
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == mSetAccountPortraitHelper.PERMISSIONS_REQUEST_CAMERA) {
//            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                mSetAccountPortraitHelper.openCamera(UserAccountReporter.UserAccountConstants.EVENT_ACCOUNT_FROM_CENTER);
//            } else {
//                UserAccountUtil.showSetPermissionDialog(this);
//            }
//        }
    }

    private void selectMale(boolean isMale) {
        if (isMale) {
            mLayoutMale.setSelected(true);
            mLayoutFemale.setSelected(false);
        } else {
            mLayoutMale.setSelected(false);
            mLayoutFemale.setSelected(true);
        }
    }

    private boolean isGenderSelected() {
        return mLayoutMale.isSelected() || mLayoutFemale.isSelected();
    }

    private String getSelectedGender() {
        if (mLayoutMale.isSelected())
            return "m";
        if (mLayoutFemale.isSelected()) {
            return "f";
        }
        return "u";
    }

    @UIHandler(UIConfig.UPDATE_NAME_SEX_SUCCESS)
    public void updateNameSexResponse() {
        finish();
    }

    @UIHandler(UIConfig.UPDATE_NAME_SEX_FAIL)
    public void updateNameSexFail() {
        showToast("更新个人资料失败");
    }
}
